<template>
  <div class="login-container">
    <!-- 顶部 -->
    <div class="absolute-lt flex-x-end p-3 w-full">
      <el-switch
        v-model="isDark"
        inline-prompt
        active-icon="Moon"
        inactive-icon="Sunny"
        @change="toggleTheme"
      />
      <lang-select class="ml-2 cursor-pointer" />
    </div>
    <!-- 注册表单 -->
    <el-card class="!border-none !bg-transparent !rounded-4% w-100 <sm:w-85">
      <div class="text-center relative">
        <h2>监督员注册</h2>
      </div>

      <el-form
        ref="loginFormRef"
        :model="regForm"
        :rules="regRules"
        class="login-form"
      >
        <el-form-item prop="sphone">
          <div class="flex-y-center w-full">
            <el-input
              v-model="regForm.sphone"
              placeholder="请输入电话"
              size="large"
              class="h-[48px]"
            />
          </div>
        </el-form-item>
        <!-- 用户名 -->
        <el-form-item prop="sname">
          <div class="flex-y-center w-full">
            <el-input
              v-model="regForm.sname"
              placeholder="请输入用户名"
              size="large"
              class="h-[48px]"
            />
          </div>
        </el-form-item>

        <!-- 密码 -->
        <el-tooltip
          :visible="isCapslock"
          :content="$t('login.capsLock')"
          placement="right"
        >
          <el-form-item prop="spassword">
            <div class="flex-y-center w-full">
              <el-input
                v-model="regForm.spassword"
                :placeholder="$t('login.password')"
                type="password"
                @keyup="checkCapslock"
                @keyup.enter="handleLogin"
                size="large"
                class="h-[48px] pr-2"
                show-password
              />
            </div>
          </el-form-item>
        </el-tooltip>

        <el-form-item prop="ssex">
          <div class="flex-y-center w-full">
            <el-select
              v-model="regForm.ssex"
              placeholder="请输入选择性别"
              size="large"
            >
              <el-option label="女" :value="0" />
              <el-option label="男" :value="1" />
            </el-select>
          </div>
        </el-form-item>

        <el-form-item prop="sbirth">
          <div class="flex-y-center w-full">
            <el-date-picker
              v-model="regForm.sbirth"
              placeholder="请输入选择出生日期"
              type="date"
              clear-icon=""
              size="large"
            />
          </div>
        </el-form-item>

        <!-- 登录按钮 -->
        <el-button
          :loading="loading"
          type="primary"
          size="large"
          class="w-full"
          @click.prevent="handleLogin"
          >注册
        </el-button>

        <!-- 账号密码提示 -->
        <div class="mt-10 text-sm">
          <span style="cursor: pointer" @click="router.replace('/login')"
            >已有账号？去登录</span
          >
        </div>
      </el-form>
    </el-card>

    <!-- ICP备案 -->
    <div class="absolute bottom-1 text-[10px] text-center" v-show="icpVisible">
      <p>
        Copyright © 2021 - 2024 youlai.tech All Rights Reserved. 有来技术
        版权所有
      </p>
      <p>皖ICP备20006496号-3</p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { useSettingsStore, useUserStore } from "@/store";
import AuthAPI from "@/api/auth";
import { LoginData } from "@/api/auth/model";
import type { FormInstance } from "element-plus";
import { LocationQuery, useRoute } from "vue-router";
import router from "@/router";
import defaultSettings from "@/settings";
import { ThemeEnum } from "@/enums/ThemeEnum";

const userStore = useUserStore();
const settingsStore = useSettingsStore();
const route = useRoute();

// Internationalization
const { t } = useI18n();

// Reactive states
const isDark = ref(settingsStore.theme === ThemeEnum.DARK);
const icpVisible = ref(true);
const loading = ref(false); // 按钮loading
const isCapslock = ref(false); // 是否大写锁定
const captchaBase64 = ref(); // 验证码图片Base64字符串
const loginFormRef = ref<FormInstance>(); // 登录表单ref
const { height } = useWindowSize();

const regForm = ref<any>({
  sphone: "",
  sname: "",
  ssex: 0,
  sbirth: "",
  spassword: "",
});

const regRules = computed(() => {
  return {
    sphone: [
      {
        required: true,
        trigger: "blur",
        message: "请输入电话",
      },
    ],
    sname: [
      {
        required: true,
        trigger: "blur",
        message: "请输入用户名",
      },
    ],
    ssex: [
      {
        required: true,
        trigger: "blur",
        message: "请输入选择性别",
      },
    ],
    sbirth: [
      {
        required: true,
        trigger: "blur",
        message: "请输入选择出生日期",
      },
    ],
    spassword: [
      {
        required: true,
        trigger: "blur",
        message: "请输入密码",
      },
      {
        min: 3,
        message: "密码至少3位数",
        trigger: "blur",
      },
    ],
  };
});

// 登录
function handleLogin() {
  loginFormRef.value?.validate((valid: boolean) => {
    if (valid) {
      AuthAPI.register(regForm.value).then((res) => {
        console.log(res);
        ElMessage({
          message: "注册成功",
          type: "success",
        });
        regForm.value = {
          sphone: "",
          sname: "",
          ssex: 0,
          sbirth: "",
          spassword: "",
        };
        router.replace("/login");
      });
    }
  });
}

// 解析 redirect 字符串 为 path 和  queryParams
function parseRedirect(): {
  path: string;
  queryParams: Record<string, string>;
} {
  const query: LocationQuery = route.query;
  const redirect = (query.redirect as string) ?? "/";

  const url = new URL(redirect, window.location.origin);
  const path = url.pathname;
  const queryParams: Record<string, string> = {};

  url.searchParams.forEach((value, key) => {
    queryParams[key] = value;
  });

  return { path, queryParams };
}

/** 主题切换 */
const toggleTheme = () => {
  const newTheme =
    settingsStore.theme === ThemeEnum.DARK ? ThemeEnum.LIGHT : ThemeEnum.DARK;
  settingsStore.changeTheme(newTheme);
};

/** 根据屏幕宽度切换设备模式 */
watchEffect(() => {
  if (height.value < 600) {
    icpVisible.value = false;
  } else {
    icpVisible.value = true;
  }
});

/** 检查输入大小写 */
function checkCapslock(event: KeyboardEvent) {
  // 防止浏览器密码自动填充时报错
  if (event instanceof KeyboardEvent) {
    isCapslock.value = event.getModifierState("CapsLock");
  }
}

onMounted(() => {
  // getCaptcha();
});
</script>

<style lang="scss" scoped>
html.dark .login-container {
  background: url("@/assets/images/login-bg-dark.jpg") no-repeat center right;
}

.login-container {
  overflow-y: auto;
  background: url("@/assets/images/login-bg.jpg") no-repeat center right;

  @apply wh-full flex-center;

  .login-form {
    padding: 30px 10px;
  }
}
</style>
